import axios from "axios";
import { Loading, Message } from 'element-ui';
import router from "./router";


let loading; //定义loading变量

function startLoading(){ //使用 Element loading-start 方法
    loading = Loading.service({
        lock:true,
        text:'加载中...',
        background:'rgba(0,0,0,0.7)',
    })
}
function endLoading(){ // 结束当前加载动画
    loading.close()
}
 
//请求拦截 
axios.interceptors.request.use(config =>{
    //加载动画
    startLoading();

    if(localStorage.eleToken){
        //设置统一header
        config.headers.Authorization = localStorage.eleToken;

    }
    return config;//返回出去
},error =>{
    //失败
    return Promise.reject(error);
})


//响应拦截
axios.interceptors.response.use(
    response =>{
        //结束加载动画
        endLoading();
        return response;
    },error =>{
        //错误提示
        endLoading();
        Message.error(error.response.data);

        //获取错误状态码
        const {status} = error.response;
        if(status == 401){
            Message.error('token失效，请重新登录！');
            //清除 token 
            localStorage.removeItem('eleToken');
            //跳转到登录页
            router.push('/login')
        }
        return Promise.reject(error)
    }
)

export default axios;